package com.chaoxin.lovehelp.aop;

import com.chaoxin.lovehelp.annotation.AuthCheck;
import com.chaoxin.lovehelp.common.enums.ErrorCode;
import com.chaoxin.lovehelp.common.exception.BusinessException;
import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.service.FellowService;
import com.chaoxin.lovehelp.common.enums.UserRoleEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验 AOP
 *
 * @author TengJay Huang
 *  
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private FellowService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
//        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        FellowEntity loginUser = userService.getLogin(request);
        // 如果被封号，直接拒绝
        if (loginUser.getRole() == 4) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR);
        }

        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

